package cn.lg.soar.system.biz.modules.auth.service;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.biz.config.SystemCacheKey;
import cn.lg.soar.system.biz.modules.auth.entity.RoleMenuRel;
import cn.lg.soar.system.biz.modules.auth.mapper.RoleMenuRelMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author luguoxiang
 * @date 2022/4/10
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class RoleMenuRelService extends ServiceImpl<RoleMenuRelMapper, RoleMenuRel> {

    /**
     * 根据角色获取菜单id
     * @param roleId
     * @return
     */
    @Cacheable(value = SystemCacheKey.ROLEID_TO_MENUIDS, key = "#p0", cacheManager = "remote")
    public List<Integer> getMenuIds(Long roleId) {
        return listObjs(
                Wrappers.<RoleMenuRel>lambdaQuery()
                        .select(RoleMenuRel::getMenuId)
                        .eq(RoleMenuRel::getRoleId, roleId),
                x -> Integer.parseInt(x.toString())
        );
    }

    /**
     * 设置角色菜单
     * @param roleId
     * @param menuIds
     */
    @CacheEvict(value = {SystemCacheKey.ROLEID_TO_MENUIDS, SystemCacheKey.ROLEID_TO_PERMITS}, key = "#p0")
    @Transactional(rollbackFor = RuntimeException.class)
    public void setRoleMenu(Long roleId, Collection<Integer> menuIds) {
        // 清空旧值
        clearByRole(roleId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(menuIds)) {
            return;
        }
        // 转换
        List<RoleMenuRel> collect = menuIds.stream()
                .distinct()
                .map(x -> {
                    RoleMenuRel data = new RoleMenuRel();
                    data.setMenuId(x);
                    data.setRoleId(roleId);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存角色菜单失败");
    }

    @CacheEvict(value = {SystemCacheKey.ROLEID_TO_MENUIDS, SystemCacheKey.ROLEID_TO_PERMITS}, key = "#p0")
    public void clearByRole(Long roleId) {
        this.remove(Wrappers.<RoleMenuRel>lambdaQuery().eq(RoleMenuRel::getRoleId, roleId));
    }

    public void clearByMenu(Integer menuId) {
        this.remove(Wrappers.<RoleMenuRel>lambdaQuery().eq(RoleMenuRel::getMenuId, menuId));
    }

}
